﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace HFController
{
    /// <summary>
    /// 集成ControllerBase类，里边可以定义通用方法
    /// </summary>
    public class AdminController : ControllerBase
    {
        /// <summary>
        /// 实例化管理员数据库层
        /// </summary>
        private hf.DAL.admin adminDAL = new hf.DAL.admin();

        /// <summary>
        /// 本类的单列对象，保证这个类在程序中只存在着一个实例
        /// </summary>
        private static AdminController _adminController;

        /// <summary>
        /// 实例化本类（单列模式实例化）
        /// 判断_adminController对象有没有实例化，实例化了直接返回，没有就实例化
        /// </summary>
        /// <returns></returns>
        public static AdminController getController()
        {
            if (_adminController == null)
            {
                _adminController = new AdminController();
            }
            return _adminController;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        public void AdminLogin(string uid, string pwd)
        {
            //实例化信息传递对象（主要是传递文字提示，跳转页面，是否执行成功等信息）
            HFModel.ResultModel result = new HFModel.ResultModel();

            //设置查询条件（把用户输入的帐号和密码当作查询条件，数据库里有，表示登录成功）
            string strWhere = "UID = '" + uid + "' and PWD = '" + pwd + "'";

            //执行数据库查询后返回的记录条数
            int total;

            //管理员列表，就是你今天补上的方法
            List<hf.Model.admin> list = adminDAL.GetAdminList(1, 1, strWhere, out total);

            //判断列表中的数据数，如果是大于0，表示有这个用户的记录，登录成功
            if (list.Count > 0)
            {
                //设置传递信息对象，表示登录成功，跳转到index.aspx页面
                result.isTrue = true;
                result.Message = "登录成功！";
                result.historyUrl = "location='login.aspx'"; //result.isTrue = false，执行
                result.goUrl = "location='index.aspx'";//result.isTrue = true，执行

                list[0].LastDatetime = DateTime.Now; //设置最后一次登录时间
                list[0].LoginCount++; //增加登录次数
                list[0].LastLoginIP = HttpContext.Current.Request.UserHostAddress.ToString(); //得到客户端IP地址

                //更新这条用户记录，主要是保存上面那三个信息
                adminDAL.Update(list[0]);

                //保存当前管理员信息到Session中
                HttpContext.Current.Session["Admin"] = list[0];
            }
            else {
                //登录失败
                result.isTrue = false;
                result.Message = "用户名或密码错误，请检查！";
                result.historyUrl = "history.go(-1)";
                result.goUrl = "history.go(-1)";
            }
            //执行提示和跳转页面。这个方法写在了基础类中，就是这个类集成的父类
            doResult(result);
        }
        
        /// <summary>
        /// 得到当前已登录管理员
        /// </summary>
        /// <returns></returns>
        public hf.Model.admin getAdmin()
        {
            return getLoginAdminInfo();
        }
        
        /// <summary>
        /// 修改管理员密码
        /// </summary>
        /// <param name="oldPWD"></param>
        /// <param name="PWD"></param>
        /// <param name="PWD1"></param>
        public void ModifyPWD(string oldPWD, string PWD, string PWD1 )
        {
            hf.Model.admin adminModel = getLoginAdminInfo();
            HFModel.ResultModel result = new HFModel.ResultModel();

            if (oldPWD != adminModel.PWD)
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
                result.Message = "当前密码错误";
                doResult(result);
            }
            else if (PWD != PWD1)
            {
                result.isTrue = false;
                result.goUrl = "history.go(-1)";
                result.historyUrl = "history.go(-1)";
                result.Message = "两次输入密码不一致";
                doResult(result);
            }
            else
            {
                adminModel.PWD = PWD;
                adminDAL.Update(adminModel);
                result.isTrue = true;
                result.goUrl = "location='../main.aspx'";
                result.historyUrl = "history.go(-1);";
                result.Message = "修改成功";
                doResult(result);
            }
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public void Logout()
        {
            //清除Session
            HttpContext.Current.Session["Admin"] = null;
            HttpContext.Current.Session.RemoveAll();
            //跳转到登录页面
            HttpContext.Current.Response.Write("<script>location='login.aspx'</script>");
        }

        /// <summary>
        /// 得到管理员列表
        /// </summary>
        /// <param name="PageStr"></param>
        /// <returns></returns>
        public List<hf.Model.admin> getAdminList(out string PageStr)
        {
            int PageSize = 20;
            int PageNumber = 1;
            if (HttpContext.Current.Request.QueryString["Page"] != null)
            {
                PageNumber = int.Parse(HttpContext.Current.Request.QueryString["Page"].ToString());
            }

            int total = 0;

            List<hf.Model.admin> list = new List<hf.Model.admin>();
            list = adminDAL.GetAdminList(PageSize, PageNumber, "", out total);
            PageStr = LLL.Pager.TrunPageHtmlCode(PageSize, PageNumber, total, "");
            return list;
        }

        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <param name="UID"></param>
        /// <param name="PWD"></param>
        /// <param name="LevelID"></param>
        public void doAddAdmin(string UID, string PWD, string LevelID ,int CityID)
        {
            HFModel.ResultModel result = new HFModel.ResultModel();

            if (UID == "")
            {
                result.isTrue = false;
                result.Message = "帐号不能为空";
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1)";
                this.doResult(result);
                return;
            }

            if (isReg(UID))
            {
                result.isTrue = false;
                result.Message = "用户名已经被注册！";
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1)";
                this.doResult(result);
                return;
            }

            if (PWD == "")
            {
                result.isTrue = false;
                result.Message = "密码不能为空";
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1)";
                this.doResult(result);
                return;
            }

            hf.Model.admin admin = this.getLoginAdminInfo();
            if (admin.CityID != 0)
            {
                result.isTrue = false;
                result.Message = "你没有权限执行此操作。";
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1)";
                this.doResult(result);
                return;
            }

            try
            {
                hf.Model.admin model = new hf.Model.admin();
                model.UID = UID;
                model.PWD = PWD;
               // model.LevelID = int.Parse(LevelID);
                model.LastLoginIP = "127.0.0.1";
                model.LastDatetime = DateTime.Now;
                model.LoginCount = 0;
                model.CityID = CityID;
                model.ID = adminDAL.Add(model);

                result.isTrue = true;
                result.Message = "添加成功！";
                result.goUrl = "location='AddAdmin.aspx';";
                result.historyUrl = "history.go(-1)";
            }
            catch
            {
                result.isTrue = false;
                result.Message = "系统问题，请联系管理员";
                result.goUrl = "history.go(-1);";
                result.historyUrl = "history.go(-1)";
            }
            this.doResult(result);
        }

        /// <summary>
        /// 验证用户名是否存在
        /// </summary>
        /// <param name="UID"></param>
        /// <returns></returns>
        private bool isReg(string UID)
        {
            int total = 0;
            List<hf.Model.admin> list = new List<hf.Model.admin>();
            list = adminDAL.GetAdminList(1, 1, "UID='" + UID + "'", out total);
            if (list.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 得到管理员
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public hf.Model.admin getAdmin(string ID)
        {
            int total = 0;
            if (ID != "")
            {
                List<hf.Model.admin> list = new List<hf.Model.admin>();
                list = adminDAL.GetAdminList(1, 1, "ID='" + ID + "'", out total);
               // list[0].Level = adminlevelDAL.GetAdminLevelList(1, 1, "ID=" + list[0].LevelID, out total)[0];
                return list[0];
            }
            else
            {
                return null;
            }
        }
    }
}
